from apps.pay.order.baseViews import *
from apps.pay.order.sceneHandle import createOrderScene, setPayMoney, cancelOrderReturnScene
from apps.common.utils.time import getFormatTime
from apps.pay.order.service_exportExcel import exportExcel
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.user.dao import UserDao
from apps.pay.wx.service import returnMoney
from apps.merchant.sku.dao import SkuDao
from apps.merchant.activity.dao import ActivityDao

def getOrders(self):
    _list = OrderDao().findAll().select_related('user', 'lessee', 'rider', 'activity')
    return _list

class OrderViewSet(BaseOrderViewSet):

    def get_queryset(self):
        _list = getOrders(self)
        if self.request.user.role.key == 'superAdmin' or self.request.user.role.key == 'admin':
            _list = _list
        else:
            _list = _list
        
        return _list

    '''创建订单'''
    @action(methods=['post'], detail=False)
    def createOrder(self, request):
        params = getRequestParams(request)
        if isEmptyStr(params.get("clientname")):
            return Response(response_message('参数clientname必填'))
        if isEmptyStr(params.get("sendType")):
            return Response(response_message('参数sendType必填'))
        data = {
            "lessee": params.get("lessee"),
            "user": request.user.id,
            "clientname": params.get("clientname"),
            "sendType": params.get("sendType"),
            'addrinfo': params.get('addrinfo'),
            'orderId': getFormatTime('%Y%m%d%H%M%S') + random_num(4),
            "remark": params.get("remark") if params.get("remark") else ''
        }
        # 默认普通订单
        data['scene'] = 'generay'
        # 设置活动参数
        if params.get("activity"):
            activity = ActivityDao().findOneByObjId(params.get("activity"))
            data['activity'] = activity.id
            # 如果存在活动参数
            if params.get("activityParams"):
                data['activityParams'] = params.get("activityParams")
            # 单独处理活动
            if activity.key == 'goldCustom':
                data['scene'] = 'goldCustom'

        # 设置实际支付金额
        data['realPay'] = setPayMoney(params, data, request.user)
        res = createOrderScene(params, data, request.user)
        return Response(res)

    '''根据orderId获取订单详情'''
    @action(methods=['post'], detail=False)
    def getOrderInfoByOrderId(self, request):
        params = getRequestParams(request)
        orderId = params.get('orderId')
        if not orderId:
            return Response(response_message('orderId参数必填'))
        order = OrderDao().findOneByOrderId(orderId)
        return Response(response_success(OrderModelSerializer(order).data))

    '''发货'''
    @action(methods=['post'], detail=False)
    def sendItem(self, request):
        params = getRequestParams(request)
        order = OrderDao().findOneByOrderId(params.get('orderId'))
        if order.orderStatus != 'WAIT_SEND':
            return Response(response_message('待发货状态才允许发货'))
        data = {'orderStatus': 'WAIT_RECEIVE'}
        if params.get('expressageinfo'):
            data['expressageinfo'] = params.get('expressageinfo')
        OrderDao().update(order.id, data)
        return Response(response_success('操作成功'))
    
    '''取消支付'''
    @action(methods=['post'], detail=False)
    def cancelPay(self, request):
        params = getRequestParams(request)
        orderId = params.get('orderId')
        if isEmptyStr(orderId):
            return Response(response_message('orderId参数缺失'))
        order = OrderDao().findOneByOrderId(orderId)
        if order.orderStatus != 'WAIT_PAY':
            return Response(response_message('待支付状态才允许取消'))
        # 返还库存
        content = json.loads(order.content)
        for item in content:
            if item.get('sku'):
                SkuDao().addStock(item.get('sku'), item.get('payCount')) 

        # 修改订单状态
        OrderDao().update(order.id, {'orderStatus': 'CANCEL'})
        return Response(response_success('取消成功'))

    '''取消订单'''
    @action(methods=['post'], detail=False)
    def cancelOrder(self, request):
        params = getRequestParams(request)
        orderId = params.get('orderId')
        if isEmptyStr(orderId):
            return Response(response_message('orderId参数缺失'))
        order = OrderDao().findOneByOrderId(orderId)
        if order.orderStatus != 'WAIT_SEND':
            return Response(response_message('待发货状态才允许取消'))
        
        # 取消订单之后
        if order.payway == 'incomes':
            OrderDao().update(order.id, {'orderStatus': 'RETURNING', 'retunMoneyTime': datetime.datetime.now()})
            # 退还积分
            UserDao().addWallet('incomes', order.user, order.realPay)
            data = {}
            data['lessee'] = order.lessee.id
            data['scene'] = 'expenseReturn'
            data['user'] = order.user.id
            data['fromUser'] = order.user.id
            data['orderId'] = order.orderId
            data['money'] = order.realPay
            data['payway'] = 'incomes'
            data['changeWay'] = 'add'
            RecordIncomesDao().create(data)
            OrderDao().update(order.id, {'orderStatus': 'HAS_RETURN'})
        elif order.payway == 'wxpay':
            # 退还款项到微信账户
            OrderDao().update(order.id, {'orderStatus': 'RETURNING', 'retunMoneyTime': datetime.datetime.now()})
            returnMoney(params)
        cancelOrderReturnScene(order.orderId)

        return Response(response_success('取消成功'))
    
    '''导出订单'''
    @action(methods=['post'], detail=False)
    def exportExcel(self, request):
        params = getRequestParams(request)
        _orders = OrderDao().findAll().filter(lessee=request.user.lessee.id)
        if params.get('currectRouteName') == 'orderList':
            _orders = _orders.filter(scene='generay')
        elif params.get('currectRouteName') == 'orderForGoldCustom':
            _orders = _orders.filter(scene='goldCustom')

        # 查询出要导出的数据
        query_params = {}
        exclude_params = {}
        if params.get('orderId'):
            query_params['orderId'] = params.get('orderId')
        if params.get('user'):
            query_params['user'] = params.get('user')
        if params.get('sendType'):
            query_params['sendType'] = params.get('sendType')
        if params.get('payway'):
            query_params['payway'] = params.get('payway')
        if params.get('orderStatus'):
            query_params['orderStatus'] = params.get('orderStatus')
        query_params['createTime__gte'] = params.get('startTime') if params.get('startTime') else datetime.datetime.now()-datetime.timedelta(days=30)
        query_params['createTime__lte'] = params.get('endTime') if params.get('endTime') else datetime.datetime.now()+datetime.timedelta(days=1)

        _orders = _orders.filter(**query_params).exclude(**exclude_params)
        fileUrl = exportExcel(_orders)
        return Response(response_success(fileUrl))

    # 更新物流信息
    @action(methods=['post'], detail=False)
    def updateExpressageNum(self, request):
        params = getRequestParams(request)
        if not params.get('orderId'):
            return Response(response_message('orderId参数缺失'))
        order = OrderDao().findOneByOrderId(params.get('orderId'))
        if params.get('expressageinfo'):
            OrderDao().update(order.id, {
                'expressageinfo': params.get('expressageinfo')
            })
        if params.get('addrinfo'):
            OrderDao().update(order.id, {
                'addrinfo': params.get('addrinfo')
            })
        return Response(response_success('操作成功'))
    